<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import config from '../../config.js';
import { useRouter } from 'vue-router';
import { marked } from 'marked';
import mermaid from 'mermaid';
import DocumentConverter from '../../documentConverter/DocumentConverter';
import { downloadFile, formatDate } from '../../documentConverter/utils';

// 配置marked
marked.setOptions({
  breaks: true,
  gfm: true
});

// 配置mermaid
mermaid.initialize({
  startOnLoad: false,
  theme: 'default'
});

// 处理Mermaid图表的函数 - 增强版
const renderMermaid = () => {
  console.log('开始渲染Mermaid图表...');
  
  // 确保在DOM更新后执行
  nextTick(() => {
    // 使用Promise确保异步执行顺序
    new Promise(resolve => setTimeout(resolve, 300))
      .then(() => {
        // 查找所有Mermaid容器
        const mermaidElements = document.querySelectorAll('.mermaid');
        console.log(`找到${mermaidElements.length}个Mermaid元素`);

        if (mermaidElements.length === 0) {
          console.log('没有找到Mermaid元素，可能是因为:\n1. 没有Mermaid代码块\n2. 代码块格式不正确\n3. markdownToHtml函数处理有误');
          return;
        }

        // 确保Mermaid已正确初始化
        if (!window.mermaid) {
          console.log('Mermaid未在window对象中，正在初始化...');
          window.mermaid = mermaid;
          mermaid.initialize({
            startOnLoad: false,
            theme: 'default',
            logLevel: 1 // 增加日志级别以便调试
          });
        }

        // 逐个渲染Mermaid图表
        const renderPromises = Array.from(mermaidElements).map(element => {
          return new Promise((resolve, reject) => {
            try {
              console.log('Mermaid元素内容:', element.textContent);
              // 确保元素有内容
              if (!element.textContent.trim()) {
                console.warn('Mermaid元素内容为空');
                element.innerHTML = '<div style="color: orange;">警告: Mermaid图表内容为空</div>';
                resolve();
                return;
              }

              // 使用元素ID作为图表ID，如果没有ID则生成随机ID
              let chartId = element.id || `mermaid-${Math.floor(Math.random() * 1000000)}`;
              console.log('渲染图表ID:', chartId);

              // 使用mermaid.render渲染图表
              mermaid.render(chartId, element.textContent, (svgCode, bindFunctions) => {
                console.log('图表渲染成功，SVG代码长度:', svgCode.length);
                element.innerHTML = svgCode;
                // 如果有绑定函数，执行它们
                if (bindFunctions && typeof bindFunctions === 'function') {
                  bindFunctions(element);
                }
                resolve();
              });
            } catch (error) {
              console.error('渲染Mermaid图表失败:', error);
              element.innerHTML = `<div style="color: red;">Mermaid图表渲染失败: ${error.message}</div>`;
              reject(error);
            }
          });
        });

        // 等待所有图表渲染完成
        Promise.all(renderPromises)
          .then(() => console.log('所有Mermaid图表渲染完成'))
          .catch(errors => console.error('部分Mermaid图表渲染失败:', errors));
      });
  });
};

// markdown转HTML函数，支持Mermaid - 增强版
const markdownToHtml = (markdown) => {
  console.log('开始转换markdown为HTML...');
  // 为避免日志过长，只打印前100个字符
  console.log('原始markdown内容前100字符:', markdown.substring(0, 100));
  
  // 检测并处理Mermaid代码块
  // 增强正则表达式，支持更多格式变体（允许mermaid后面有空格、换行或立即开始代码）
  const mermaidRegex = /```mermaid\s*(?:\n|\r\n)?([\s\S]*?)\n```/g;
  
  // 添加额外的日志信息
  const mermaidMatches = markdown.match(mermaidRegex);
  if (mermaidMatches) {
    console.log(`发现${mermaidMatches.length}个Mermaid代码块`);
    mermaidMatches.forEach((match, index) => {
      // 只打印匹配的前50个字符
      console.log(`Mermaid代码块${index+1}前50字符:`, match.substring(0, 50));
    });
  } else {
    console.log('没有发现Mermaid代码块');
    // 尝试检测可能的格式问题
    if (markdown.includes('```mermaid')) {
      console.log('警告: 发现了```mermaid标记，但正则表达式未匹配到，可能是格式问题');
      // 尝试找出问题所在
      const mermaidIndex = markdown.indexOf('```mermaid');
      const surroundingText = markdown.substring(
        Math.max(0, mermaidIndex - 20), 
        Math.min(markdown.length, mermaidIndex + 100)
      );
      console.log('问题区域上下文:', surroundingText);
    }
  }
  
  // 先进行marked解析
  let html = marked.parse(markdown);
  
  // 统计并替换为mermaid容器，并添加唯一ID
  let mermaidCount = 0;
  const replacedHtml = html.replace(mermaidRegex, (match, code) => {
    mermaidCount++;
    const uniqueId = `mermaid-chart-${Date.now()}-${mermaidCount}`;
    console.log(`创建Mermaid容器，ID: ${uniqueId}`);
    return `<div id="${uniqueId}" class="mermaid">${code}</div>`;
  });
  
  // 验证替换结果
  if (mermaidCount > 0) {
    console.log(`成功替换${mermaidCount}个Mermaid代码块为容器`);
  } else if (markdown.includes('```mermaid')) {
    console.log('警告: 虽然发现了```mermaid标记，但未能成功替换为Mermaid容器');
  }
  
  // 为避免日志过长，只打印转换后HTML的前200个字符
  console.log('转换后HTML前200字符:', replacedHtml.substring(0, 200));
  return replacedHtml;
};

// 聊天记录
const messages = ref([]);
// 用户输入
const userInput = ref('');
// 加载状态
const loading = ref(false);
// 错误信息
const error = ref('');
// 选择的模型
const selectedModel = ref('default');
// 模型列表
const modelList = ref([]);
const router = useRouter();

// 导出相关变量
const exportFormat = ref('pdf');
const exportScope = ref('latest');
const isExporting = ref(false);
const exportStatus = ref('');

// 导出消息的方法
const exportMessages = async () => {
  if (messages.value.length === 0) {
    exportStatus.value = '没有可导出的聊天记录';
    return;
  }
  
  isExporting.value = true;
  exportStatus.value = '正在准备导出...';
  
  try {
    const converter = new DocumentConverter();
    let blob;
    let filename = `聊天记录_${formatDate(new Date())}`;
    
    // 收集要导出的内容
    let content = '';
    if (exportScope.value === 'latest') {
      // 查找最新的AI回复
      for (let i = messages.value.length - 1; i >= 0; i--) {
        if (messages.value[i].role === 'ai') {
          content = messages.value[i].content;
          break;
        }
      }
      if (!content) {
        exportStatus.value = '没有找到AI回复';
        return;
      }
    } else {
      // 导出所有历史记录
      messages.value.forEach(msg => {
        content += `${msg.role === 'user' ? '你' : 'AI'}: ${msg.content}\n\n`;
      });
    }
    
    // 根据选择的格式进行转换
    switch (exportFormat.value) {
      case 'ppt':
        blob = await converter.convertToPPT(content, filename);
        filename += '.pptx';
        break;
      case 'word':
        blob = await converter.convertToWord(content, filename);
        filename += '.docx';
        break;
      case 'pdf':
      default:
        blob = await converter.convertToPDF(content, filename);
        filename += '.pdf';
    }
    
    // 下载文件
    downloadFile(blob, filename);
    exportStatus.value = '导出成功！文件已开始下载';
  } catch (error) {
    console.error('导出失败:', error);
    exportStatus.value = `导出失败: ${error.message}`;
  } finally {
    isExporting.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  // 加载模型列表
  loadModelList();
});

// 加载模型列表
const loadModelList = async () => {
  try {
    const response = await axios.get(`${config.api.baseUrl}/api/ai/models`);
    modelList.value = response.data;
    console.log('模型列表加载成功:', modelList.value);
  } catch (err) {
    console.error('加载模型列表失败:', err);
    error.value = '加载模型列表失败: ' + (err.response?.data?.error || err.message);
  }
};

// 生成消息内容
const generateMessageContent = () => {
  return userInput.value;
};

// 发送消息
const sendMessage = async () => {
  let content = generateMessageContent();
  if (!content.trim()) return;

  // 添加用户消息到聊天记录
  messages.value.push({
    role: 'user',
    content: content
  });

  // 清空输入
  userInput.value = '';
  loading.value = true;
  error.value = '';

  try {
    // 发送请求到后端API
    const response = await axios.post(`${config.api.baseUrl}${config.api.chatEndpoint}`, {
      message: messages.value[messages.value.length - 1].content,
      modelName: selectedModel.value === 'default' ? null : selectedModel.value
    });

    // 添加AI回复到聊天记录
    messages.value.push({
      role: 'ai',
      content: response.data.response,
      model: response.data.modelUsed
    });

    // 使用nextTick确保DOM已更新，再执行渲染
    nextTick(() => {
      // 再增加一个小延迟，确保所有内容都已处理完毕
      setTimeout(() => {
        renderMermaid();
      }, 300);
    });
  } catch (err) {
    error.value = '发送请求失败: ' + (err.response?.data?.error || err.message);
    console.error('API请求失败:', err);
  } finally {
    loading.value = false;
  }
};

// 监听回车键
const handleKeyPress = (e) => {
  if (e.key === 'Enter' && !loading.value) {
    sendMessage();
  }
};

// 跳转到股票列表
const goToStockList = () => {
  router.push('/stocks');
};

// 跳转到股票分析
const goToStockAnalysis = () => {
  router.push('/stocks/analysis');
};
// 返回首页
const goToHome = () => {
  router.push('/');
}

</script>

<template>
  <div class="chat-container">
    <div class="header-actions">
      <button @click="goToHome" class="back-button">返回首页</button>
    </div>
    <h1>AI聊天界面</h1>

    <div class="navigation">
      <button @click="goToStockList">股票管理</button>
      <button @click="goToStockAnalysis">股票分析</button>
    </div>

    <div class="model-selection">
      <label for="model-select">选择AI模型:</label>
      <select id="model-select" v-model="selectedModel">
        <option value="default">默认模型</option>
        <option v-for="model in modelList" :key="model.code" :value="model.code">
          {{ model.name }}
        </option>
      </select>
    </div>

    <div class="export-options">
      <label for="export-format">导出格式:</label>
      <select id="export-format" v-model="exportFormat">
        <option value="pdf">PDF</option>
        <option value="word">Word</option>
        <option value="ppt">PPT</option>
      </select>
      
      <label for="export-scope">导出范围:</label>
      <select id="export-scope" v-model="exportScope">
        <option value="latest">最新一次</option>
        <option value="all">所有历史</option>
      </select>
      
      <button @click="exportMessages" :disabled="isExporting">导出</button>
    </div>

    <div v-if="exportStatus" class="export-status">{{ exportStatus }}</div>

    <div class="chat-messages">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <div class="message-header">
          <span class="message-role">{{ msg.role === 'user' ? '你' : 'AI' }}</span>
          <span v-if="msg.model" class="message-model">({{ msg.model === 'alibaba' ? '阿里大模型' : msg.model === 'deepseek' ? 'DeepSeek' : msg.model }})</span>
        </div>
        <div class="message-content" v-html="msg.role === 'ai' ? markdownToHtml(msg.content) : msg.content"></div>
      </div>
      <div v-if="loading" class="loading-indicator">
        <div class="spinner"></div>
        <span>AI正在思考...</span>
      </div>
      <div v-if="error" class="error-message">{{ error }}</div>
    </div>

    <div class="input-area">
      <textarea
        v-model="userInput"
        @keypress="handleKeyPress"
        placeholder="请输入消息..."
        :disabled="loading"
      ></textarea>
      <button @click="sendMessage" :disabled="loading">发送</button>
    </div>
  </div>
</template>

<style scoped>
.header-actions {
  display: flex;
  justify-content: flex-start;
  padding: 10px;
}

.back-button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #2980b9;
}

.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
}

.navigation {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.navigation button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.navigation button:hover {
  background-color: #3aa876;
}

.model-selection {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.export-options {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.export-options label {
  margin-right: 5px;
}

.export-options button {
  padding: 8px 16px;
  background-color: #9b59b6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.export-options button:hover {
  background-color: #8e44ad;
}

.export-options button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.export-status {
  text-align: center;
  margin-bottom: 10px;
  color: #555;
}

.model-selection label {
  margin-right: 10px;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
}

.message.user {
  background-color: #e3f2fd;
  margin-left: auto;
}

.message.ai {
  background-color: #f1f8e9;
}

.message-content {
  word-wrap: break-word;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-weight: bold;
}

.message-role {
  color: #555;
}

.message-model {
  font-size: 12px;
  color: #888;
  font-weight: normal;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  color: #666;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #09f;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  color: #e74c3c;
  padding: 10px;
  background-color: #fadbd8;
  border-radius: 4px;
}

.input-area {
  display: flex;
  gap: 10px;
}

.input-area textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
  height: 80px;
}

.input-area button {
  padding: 10px 20px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  align-self: flex-end;
}

.input-area button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}
</style>